//
//  PostRequestionViewController.m
//  HelloWorld
//
//  Created by MJiao on 15/6/25.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "PostRequestionViewController.h"
#import "DataSourceManager.h"
#import "KVNProgress.h"
#import "AFHTTPRequestOperationManager.h"
#import "UserManager.h"
#import "PECropViewController.h"
#import "PostAnswerViewController.h"
#import "SCNavigationController.h"
#import "TOCropViewController.h"
#import "CommonUtils.h"

@interface PostRequestionViewController () <TOCropViewControllerDelegate>

@property(strong, nonatomic) NSMutableArray *gradeViewArray;
@property(strong, nonatomic) NSMutableArray *subjectViewArray;
@property(strong, nonatomic) NSString *selectedGradeName;
@property(strong, nonatomic) NSString *selectedSubjectName;

@end

@implementation PostRequestionViewController

- (IBAction)clickCamera:(id)sender {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:nil];
    } else {
        
        SCNavigationController *nav = [[SCNavigationController alloc] init];
        nav.scNaigationDelegate = self;
        [nav showCameraWithParentController:self];
        
//        UIImagePickerController *imagePickerController = [UIImagePickerController new];
//        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
//        imagePickerController.delegate = self;
//        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate

/**
*  拍照完成后调用
*
*  @param navigationController <#navigationController description#>
*  @param image                <#image description#>
*/
- (void)didTakePicture:(SCNavigationController*)navigationController image:(UIImage*)image
{
//    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
//    PECropViewController *controller = [[PECropViewController alloc] init];
//    controller.delegate = self;
//    controller.image = image;
    [navigationController dismissModalViewControllerAnimated:NO];
//    [self.navigationController showViewController:controller sender:self];

    TOCropViewController *cropController = [[TOCropViewController alloc] initWithImage:image];
    cropController.delegate = self;
    [self presentViewController:cropController animated:YES completion:nil];

    //[self.navigationController showViewController:cropController sender:self];
}

- (void)didTakePictureOther
{
    [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:nil];

}

/**
* 裁剪图片后返回
*/
- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle {
    self.selectImageView.image = image;
    CGRect viewFrame = [self.view convertRect:self.selectImageView.frame toView:self.navigationController.view];

    [cropViewController dismissAnimatedFromParentViewController:self withCroppedImage:image toFrame:viewFrame completion:^{

    }];

    [[DataSourceManager shareDataSourceManager] setSelectImage:image];

    [[DataSourceManager shareDataSourceManager] setHasSelectedImage:YES];

}



- (void)assembleSubjectViewArray {
    self.subjectViewArray = [[NSMutableArray alloc] init];

    NSArray *containerRow3View = [self.subjectRowView1ContainerView subviews];
    for (UIView *subview in containerRow3View) {
        if(![subview subviews] || [[subview subviews] count] ==0){
            continue;
        }
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if (btnView && [btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;

            [self.subjectViewArray addObject:btn];
        }
    }
    NSArray *containerRow4View = [self.subjectRowView2Container subviews];
    for (UIView *subview in containerRow4View) {
        if(![subview subviews] || [[subview subviews] count] ==0){
            continue;
        }
        UIView *btnView = [[subview subviews] objectAtIndex:0];

        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;

            [self.subjectViewArray addObject:btn];
        }
    }

}

- (void)assembleGradeViewArray {

    self.gradeViewArray = [[NSMutableArray alloc] init];

    NSArray *containerRow1View = [self.gradeRowView1ContainerView subviews];
    for (UIView *subview in containerRow1View) {
        if(![subview subviews] || [[subview subviews] count] ==0){
            continue;
        }
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;
            if(![[[btn titleLabel] text] isEqualToString:@"Button"]){
                [self.gradeViewArray addObject:btn];
            }
        }
    }
    NSArray *containerRow2View = [self.gradeRowView2ContainerView subviews];
    for (UIView *subview in containerRow2View) {
        if(![subview subviews] || [[subview subviews] count] ==0){
            continue;
        }
        UIView *btnView = [[subview subviews] objectAtIndex:0];
        if ([btnView isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *) btnView;
            if (![[[btn titleLabel] text] isEqualToString:@"Button"]) {
                [self.gradeViewArray addObject:btn];
            }
        }
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self assembleSubjectViewArray];
    [self assembleGradeViewArray];

    self.selectedGradeName = @"";
    self.selectedSubjectName = @"";


    [[DataSourceManager shareDataSourceManager] setHasSelectedImage:NO];

    // Do any additional setup after loading the view.
    self.textView.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.2].CGColor;
    self.textView.layer.borderWidth = 1.0;

    self.textView.layer.cornerRadius = 5;
    self.textView.layer.masksToBounds = YES;

    self.textView.placeholder = @"请描述您的问题";
    [self.textView setText:@""];

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    singleTap.numberOfTapsRequired = 1;

    [self.ivPhoto setUserInteractionEnabled:YES];
    [self.ivPhoto addGestureRecognizer:singleTap];


    [self.selectImageView setUserInteractionEnabled:YES];
    [self.selectImageView addGestureRecognizer:singleTap];

    NSString *title = [[UserManager shareUserManager] curUser].gradeName;

    if (title.length > 0) {
        self.selectedGradeName = title;
        
        for (UIButton *btn in  self.gradeViewArray) {
            if ([[[btn titleLabel] text] isEqualToString:title]) {
                [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
            } else if(![[[btn titleLabel] text] isEqualToString:@"Button"]){
                [btn setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
            }
        }
    }

    self.isFirstOpenThisControllerView = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([[DataSourceManager shareDataSourceManager] hasSelectedImage]) {
        UIImage *selectImage = [[DataSourceManager shareDataSourceManager] selectImage];
        [self.selectImageView setImage:selectImage];

        [self.lbTip setHidden:YES];
        [self.ivPhoto setHidden:YES];
    }else{
        [self.lbTip setHidden:NO];
        [self.ivPhoto setHidden:NO];
    }

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[DataSourceManager shareDataSourceManager] setHasSelectedImage:NO];

    BOOL tIsHidden = YES;
    [self.viewSelectSubject setHidden:tIsHidden];

    if (!isViewSelectSubjectShow) {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_up_arrow"]];
    } else {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_down_arrow"]];

    }
}

- (void)tapDetected {
    //第一步 做登录检查判断
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }
    [self clickCamera:nil];
//    [self performSegueWithIdentifier:@"ToSelectPhotoIdentifier" sender:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/**
*  选择年级
*
*  @param sender <#sender description#>
*/
- (IBAction)btnSelectGradeAction:(id)sender {
    UIButton *btnGrade = ((UIButton *) sender);
    NSString *title = [[btnGrade titleLabel] text];
    if ( [title isEqualToString:@"Button"]) {
        return;
    }
    self.selectedGradeName = title;

    for (UIButton *btn in  self.gradeViewArray) {
        if ([[[btn titleLabel] text] isEqualToString:title]) {
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        } else if(![[[btn titleLabel] text] isEqualToString:@"Button"]){
            [btn setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
        }
    }
}
- (IBAction)btnSelectSubject:(id)sender {

    [self switchSelectSubjectShowView];
}
/**
*   选择学科
*
*  @param sender <#sender description#>
*/
- (IBAction)btnSubjectSelectAction:(id)sender {

    UIButton *btnSubject = ((UIButton *) sender);
    NSString *title = [[btnSubject titleLabel] text];
    if ( [title isEqualToString:@"Button"] || [title length]==0) {
        return;
    }
    self.selectedSubjectName = title;

    for (UIButton *btn in  self.subjectViewArray) {
        if ([[[btn titleLabel] text] isEqualToString:title]) {
            [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        } else if(![[[btn titleLabel] text] isEqualToString:@"Button"]){
            [btn setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
        }
    }
}

- (void)switchSelectSubjectShowView {
    isViewSelectSubjectShow = !isViewSelectSubjectShow;
    BOOL tIsHidden = isViewSelectSubjectShow;
    [self.viewSelectSubject setHidden:tIsHidden];


    if (!isViewSelectSubjectShow) {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_up_arrow"]];
    } else {
        [self.ivArrowFlag setImage:[UIImage imageNamed:@"blue_down_arrow"]];

    }
}
/**
*  确认选择
*
*  @param sender <#sender description#>
*/
- (IBAction)btnConfirmSelectAction:(id)sender {
    if ([self.selectedGradeName length] == 0) {
        [KVNProgress showErrorWithStatus:@"请选择年级"];
        return;
    }
    if ([self.selectedSubjectName length] == 0) {
        [KVNProgress showErrorWithStatus:@"请选择科目"];
        return;
    }



    NSString *title = @"帮帮";
    if ([self.selectedSubjectName isEqualToString:@""] || [self.selectedGradeName isEqualToString:@""]) {
        title = @"年级、科目";
    } else {
        title = [NSString stringWithFormat:@"%@%@", self.selectedGradeName,self.selectedSubjectName];
    }
    //NSLog(@"新的Title:%@",title);
    [self.btnSelectCategory setTitle:title forState:UIControlStateNormal ];
    [self.btnSelectCategory setTitle:title forState:UIControlStateHighlighted ];
    [self.btnSelectCategory setTitle:title forState:UIControlStateSelected ];

    if (self.isFirstOpenThisControllerView) {
        self.isFirstOpenThisControllerView = NO;
        [self clickCamera:nil];
    } else {
        [self switchSelectSubjectShowView];
    }
   
}


- (void)initSubjectAndGradeSelectViewState {
//    NSArray *views = [self.viewSelectSubject subviews];
//    UIView *containerView = [views objectAtIndex:0];
//    for (UIView *subview in [containerView subviews]) {
//        if ([subview isKindOfClass:[UIButton class]] && subview.tag >= 0 && subview.tag <= 19) {
//            UIButton *btnGrade = (UIButton *) subview;
//
//            if (subview.tag == 0 || subview.tag == 10) {
//                [btnGrade setTitleColor:[UIColor colorWithRed:0 green:0.478431 blue:1 alpha:1] forState:UIControlStateNormal];
//            } else {
//                [btnGrade setTitleColor:[UIColor colorWithRed:0.333333 green:0.333333 blue:0.333333 alpha:1] forState:UIControlStateNormal];
//            }
//        }
//
//    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnPostRequestionAction:(id)sender {
    //第一步 做登录检查判断
    if ([[UserManager shareUserManager] curUser].userId == -1) {
        [self performSegueWithIdentifier:@"toLoginIdentifier" sender:self];
        return;
    }

    if ([self.selectedGradeName length]==0) {
        [KVNProgress showErrorWithStatus:@"请选择年级"];
        return;
    }
    if ([self.selectedSubjectName length]==0) {
        [KVNProgress showErrorWithStatus:@"请选择科目"];
        return;
    }

    NSString *content = [self.textView text];
    if (![[DataSourceManager shareDataSourceManager] hasSelectedImage]) {
        [KVNProgress showErrorWithStatus:@"请上传图片"];
        return;
    }
    if (content == nil || content.length == 0) {
        [KVNProgress showErrorWithStatus:@"请填写您的问题描述"];
        [self.textView becomeFirstResponder];
        return;
    }
    [KVNProgress showWithStatus:@"问题发布中..."];


    NSString *urlString = @"http://121.41.91.36:8888/api/help/upload";

    // just testing
    AFHTTPRequestOperationManager * httpManager = [[AFHTTPRequestOperationManager alloc] init];
    [httpManager.requestSerializer setTimeoutInterval:60];  //Time out after 25 seconds

//    NSData *imageData = UIImagePNGRepresentation(self.ivPhoto.image);
//    [UIImageJPEGRepresentation(self.ivPhoto.image, 0.8) base64EncodedString];
//    NSData *imageData = UIImageJPEGRepresentation(self.selectImageView.image, 0.7);
    NSData *imageData = [CommonUtils imageWithImage:self.selectImageView.image scaled:0.7f];
    NSString *baseEncodedStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

//    NSData* imageData = [UIImageJPEGRepresentation(self.ivPhoto.image, 0.8) base64EncodedString];
//    [imageData base64EncodedString]
    httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *parameters = @{@"imageUrl": baseEncodedStr};

    [httpManager POST:urlString
           parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                //[formData appendPartWithFormData:imageData name:@"imageUrl"];

            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
             
                NSString *content =[ NSString stringWithCString:[responseObject bytes] encoding:NSUTF8StringEncoding];
                NSLog(@"ImageURL:%@",content);
                
                [self uploadAttachParam:content];

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"error:%@",error);
                // 结束登陆提示
                [KVNProgress dismiss];
                [KVNProgress showErrorWithStatus:@"上传超时,请再试"];
            }];

}

-(void )uploadAttachParam:(NSString*) imageUrl{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    NSInteger  userId = [[[UserManager shareUserManager] curUser] userId];
    NSString * userIdStr = [NSString stringWithFormat:@"%ld",userId];

    NSDictionary *parameters = @{
            @"userId": userIdStr,
            @"imageUrl":imageUrl,
            @"Contents": [self.textView text],
            @"SubjectName": self.selectedSubjectName,
            @"GradeName": self.selectedGradeName
    };
    NSString *urlString = @"http://121.41.91.36:8888/api//help/sethelp";
    [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }

        [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"] completion:^{
            // Things you want to do after the HUD is gone.
            [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"NeedRefreshQuestionNotify" object:nil]];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}
@end
